package com.miaosha.access;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;

@Component
public class RolePermissionMapping {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private SetOperations<String, Object> setOperations;

    @PostConstruct
    public void init() {
        this.setOperations = redisTemplate.opsForSet();
    }

    public void addPermissionToRole(Long roleId, String permission) {
        setOperations.add("role:" + roleId, permission);
    }

    public void removePermissionFromRole(Long roleId, String permission) {
        setOperations.remove("role:" + roleId, permission);
    }

    public Set<Object> getPermissionsForRole(Long roleId) {
        return setOperations.members("role:" + roleId);
    }

    public boolean hasPermission(Long roleId,Object permission) {
        Set<Object> permissions = setOperations.members("role:" + roleId);
        return permissions.contains(permission);
    }
}